var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var jwt = require('jsonwebtoken');
var db = require('./utils/db')


//引入router
// 登录
var loginRouter = require('./routers/login')
// 员工端
var basicRouter = require('./routers/employee/basic')
var bookingorderRouter = require('./routers/employee/bookingorder')
var foodmanageRouter = require('./routers/employee/foodmanage')
var historyorderRouter = require('./routers/employee/historyorder')
var homepageemployeeRouter = require('./routers/employee/homepageemployee')
var numeralorderRouter = require('./routers/employee/numeralorder')
var orderRouter = require('./routers/employee/order')
var orderdetailRouter = require('./routers/employee/orderdetail')
var personalRouter = require('./routers/employee/personal')
var singleRouter = require('./routers/employee/single')
var tableRouter = require('./routers/employee/table')
var todayorderRouter = require('./routers/employee/todayorder')
// 管理员端
var cashierwaterRouter = require('./routers/manage/cashierwater')
var codeorderRouter = require('./routers/manage/codeorder')
var couponRouter = require('./routers/manage/coupon')
var foodRouter = require('./routers/manage/food')
var foodstockRouter = require('./routers/manage/foodstock')
var foodwaterRouter = require('./routers/manage/foodwater')
var homepageRouter = require('./routers/manage/homepage')
var indentRouter = require('./routers/manage/indent')
var inventoryRouter = require('./routers/manage/inventory')
var loginlogRouter = require('./routers/manage/loginlog')
var payRouter = require('./routers/manage/pay')
var productRouter = require('./routers/manage/product')
var revenuereportRouter = require('./routers/manage/revenuereport')
var smallprogramRouter = require('./routers/manage/smallprogram')
var stocktakingRouter = require('./routers/manage/stocktaking')
var storeRouter = require('./routers/manage/store')
var tablelistRouter = require('./routers/manage/tablelist')
var workerRouter = require('./routers/manage/worker')

var app = express();




app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With,token');
  req.method === 'OPTIONS' ? res.status(204).end() : next();
});

app.all('*', function (req, res, next) {
  //看是不是登录页面过来的
  if (req.url.startsWith('/login')) {
    console.log('login');
    next();
  } else {
    console.log(1111);
    const token = req.headers.token;
    if (!token) { //判断前端有没有传token
      res.status(401).send({ msg: '请发送token' }).end();
    }
    //解密token
    jwt.verify(token, 'web281', (err, decoded) => {
      if (err) {
        res.status(401).send({ msg: 'token错误,验证失败' }).end()
      } else {
        console.log(decoded)
        let sql = 'select * from user where user_id=' + decoded.data.user_id + ';';
        db(sql, {}, function (err, data) {
          console.log(err, data);
          if (err) {
            //秘钥已经过期了
            res.status(401).send({ msg: 'token过期了' }).end()
          } else {
            if (data.length) {
              next();
            } else {
              //秘钥已经过期了
              res.status(401).send({ msg: 'token过期了' }).end()
            }

          }
        })
      }
    });
  }
})


// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


//在此处使用router
// 登录
app.use('/login', loginRouter)
// 员工端
app.use('/basic', basicRouter)
app.use('/bookingorder', bookingorderRouter)
app.use('/foodmanage', foodmanageRouter)
app.use('/historyorder', historyorderRouter)
app.use('/homepageemployee', homepageemployeeRouter)
app.use('/numeralorder', numeralorderRouter)
app.use('/order', orderRouter)
app.use('/orderdetail', orderdetailRouter)
app.use('/personal', personalRouter)
app.use('/single', singleRouter)
app.use('/table', tableRouter)
app.use('/todayorder', todayorderRouter)
// 管理员端
app.use('/cashierwater', cashierwaterRouter)
app.use('/codeorder', codeorderRouter)
app.use('/coupon', couponRouter)
app.use('/food', foodRouter)
app.use('/foodstock', foodstockRouter)
app.use('/foodwater', foodwaterRouter)
app.use('/homepage', homepageRouter)
app.use('/indent', indentRouter)
app.use('/inventory', inventoryRouter)
app.use('/loginlog', loginlogRouter)
app.use('/pay', payRouter)
app.use('/product', productRouter)
app.use('/revenuereport', revenuereportRouter)
app.use('/smallprogram', smallprogramRouter)
app.use('/stocktaking', stocktakingRouter)
app.use('/store', storeRouter)
app.use('/tablelist', tablelistRouter)
app.use('/worker', workerRouter)


// catch 404 and forward to error handler
// app.use(function (req, res, next) {
//   next(createError(404));
// });

// error handler
// app.use(function (err, req, res, next) {
//   // set locals, only providing error in development
//   res.locals.message = err.message;
//   res.locals.error = req.app.get('env') === 'development' ? err : {};

//   // render the error page
//   res.status(err.status || 500);
//   res.render('error');
// });


//端口号
app.listen(3000, () => {
  console.log('项目启动了')
})

// module.exports = app;